package com.tianhui.consignortwofei.mvp.ui.activity.hetong;

import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.fgs.common.CommonPresenter;
import com.fgs.common.CommonResponse;
import com.fgs.common.CommonView;
import com.fgs.common.entity.PictureInfo;
import com.fgs.common.entity.UploadPictureInfo;
import com.fgs.common.other.CommonEvent;
import com.fgs.common.pictureSelector.SelectPicture;
import com.fgs.common.progress.ExceptionHandle;
import com.fgs.common.progress.ObserverResponseListener;
import com.fgs.common.uploadPicture.IUploadPicture;
import com.fgs.common.uploadPicture.UploadPicture;
import com.fgs.common.utils.LogUtil;
import com.fgs.common.widget.itemView.ClickItemView;
import com.fgs.common.widget.itemView.SettingItemView;
import com.luck.picture.lib.entity.LocalMedia;
import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.base.BaseActivity;
import com.tianhui.consignortwofei.base.BaseFragment;
import com.tianhui.consignortwofei.constant.Config;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.jPush.PushMessageReceiver;
import com.tianhui.consignortwofei.manager.EventBusManage;
import com.tianhui.consignortwofei.manager.SharedPreferenceManager;
import com.tianhui.consignortwofei.mvp.model.UserInfoModel;
import com.tianhui.consignortwofei.mvp.model.hetong.ContractInfo;
import com.tianhui.consignortwofei.mvp.model.hetong.ContractModel;
import com.tianhui.consignortwofei.mvp.model.hetong.ShenPiTiJiaoOneBean;
import com.tianhui.consignortwofei.mvp.ui.activity.HeTongWatchActivity;
import com.tianhui.consignortwofei.other.EventWhat;
import com.tianhui.consignortwofei.other.PictureType;
import com.tianhui.consignortwofei.utils.BadgerUtil;
import com.tianhui.consignortwofei.utils.shuiyin.WaterMarkView;
import com.xuexiang.xui.widget.dialog.materialdialog.DialogAction;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import me.leolin.shortcutbadger.ShortcutBadger;

/**
 * @author fgs
 * @date 2020/4/28
 * @description
 **/
public class HeTongShenPiBossActivity extends BaseActivity {

    @BindView(R.id.civ_duixiang)
    ClickItemView civ_duixiang;
    @BindView(R.id.rv_shenhe_image)
    RecyclerView rv_shenhe_image;
    @BindView(R.id.et_xiangqing)
    EditText et_xiangqing;
    @BindView(R.id.tv_save)
    TextView tv_save;

    @BindView(R.id.webview)
    WebView webView;
    @BindView(R.id.wmv)
    WaterMarkView wmv;

    @BindView(R.id.tv_zhongshen)
    TextView tv_zhongshen;

    @BindView(R.id.civ_jiedian)
    SettingItemView civ_jiedian;




    private ContractInfo mContractInfo;

    private ShenPiTiJiaoOneBean shenPiTiJiaoOneBean;
    private String contractno="";
    private UserInfoModel driverModel;

    @Override
    public int getLayoutId() {
        return R.layout.activity_hetong_shenpi_boss;
    }

    @Override
    public CommonPresenter createPresenter() {
        return null;
    }

    @Override
    public CommonView createView() {
        return null;
    }

    @Override
    public void init() {
        setTitle("审批");
//        setSubTitle("刷新");

        driverModel = new UserInfoModel();
        contractModel = new ContractModel();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null && !bundle.isEmpty()) {
            contractno = bundle.getString("danHao");
            mContractInfo=new ContractInfo();
            mContractInfo.contractno=contractno;
//            mContractInfo = bundle.getParcelable(KeyValue.KEY_CONTRACT_INFO);
//            contractno=mContractInfo.contractno;
//            initWeb();
        }



//        shenPiTiJiaoOneBean = new ShenPiTiJiaoOneBean();


        //清除角标
        try {
            PushMessageReceiver.msgNum=0;
            ShortcutBadger.removeCount(this);
            BadgerUtil.addBadger(this, 0);
        }catch (Exception e){
            LogUtil.print(e.toString());
        }

        initImageSelect();
        getShenHeInfo();
    }


    private void initWeb() {


        // 启用JavaScript
        webView.getSettings().setJavaScriptEnabled(true);

        // 设置WebView客户端
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setSupportZoom(true); // 允许缩放
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDisplayZoomControls(false);// 显示缩放工具栏

        String token = SharedPreferenceManager.getInstance().getToken();
        // 加载网络PDF，使用Google Docs Viewer
//        String pdfUrl = "http://example.com/yourpdf.pdf";

        String pdfUrl = Config.baseUrl+"contract/contractView?fileName="+mContractInfo.contractno+"&token="+token;
        webView.loadUrl("file:///android_asset/indexpdf.html?" + pdfUrl);


    }

    @Override
    public BaseFragment createFragment() {
        return null;
    }


//    @Override
//    public void onSubtitleClick() {
//        showCreateTipDialog(contractInfo);
//    }


    @OnClick(R.id.civ_duixiang)
    public void duiXiang() {
        openActivity(DuiXiangSelectListActivity.class);
    }

    @OnClick(R.id.civ_watch)
    public void watchHeTong() {

        Bundle bundle = new Bundle();
        bundle.putParcelable(KeyValue.KEY_CONTRACT_INFO, mContractInfo);
        openActivity(HeTongWatchActivity.class, bundle);//查看合同
    }


    @OnClick(R.id.tv_save)
    public void infoSave() {
        //同意审核
        if ("1".equals(shenPiTiJiaoOneBean.getEnd())){
            infoZhongShen();
        }else {


            if (null == shenPiTiJiaoOneBean.getPlanuser() || TextUtils.isEmpty(shenPiTiJiaoOneBean.getPlanuser())) {
                showToast("请选择下一级审批人");
                return;

            }

//        if (null== shenPiTiJiaoOneBean.getContractno()||TextUtils.isEmpty(shenPiTiJiaoOneBean.getContractno())){
//            showToast("未填获取到合同编号");
//            return;
//
//        }


            String text = et_xiangqing.getText().toString();
            shenPiTiJiaoOneBean.setRemark(text);
            shenPiTiJiaoOneBean.setStatus("1");
            postShenHeInfo();
        }

    }



    @OnClick(R.id.tv_bohui)
    public void infoBoHui() {
        //驳回审核
//        if (null== shenPiTiJiaoOneBean.getPlanuser()||TextUtils.isEmpty(shenPiTiJiaoOneBean.getPlanuser())){
//            showToast("请选择审批对象");
//            return;
//
//        }

//        if (null== shenPiTiJiaoOneBean.getContractno()||TextUtils.isEmpty(shenPiTiJiaoOneBean.getContractno())){
//            showToast("未填获取到合同编号");
//            return;
//
//        }


        String text = et_xiangqing.getText().toString();
        shenPiTiJiaoOneBean.setRemark(text);
        shenPiTiJiaoOneBean.setStatus("2");
        postShenHeInfo();

    }



    @OnClick(R.id.tv_zhongshen)
    public void infoZhongShen() {
        //终审
        String text = et_xiangqing.getText().toString();
        shenPiTiJiaoOneBean.setRemark(text);
        shenPiTiJiaoOneBean.setStatus("1");
        shenPiTiJiaoOneBean.setFinals("1");
        postShenHeInfo();

    }


    @Override
    public void onEvent(CommonEvent event) {
        super.onEvent(event);
        switch (EventWhat.valueOf(event.getWhat())) {
            case EVENT_REFRESH_DUIXIANG_LIST:
                String message = event.getMessage();
                String messageSource = event.getMessageSource();
                civ_duixiang.setContent(message);
                shenPiTiJiaoOneBean.setPlanuser(messageSource);
                break;

        }
    }




    private SelectPicture mVehicleImageSelectPicture;
    List<String> mVehicleImageSelectPictureList = new ArrayList<>();

    private void initImageSelect() {
        mVehicleImageSelectPicture = new SelectPicture();
        mVehicleImageSelectPicture.setMaxSelectNum(1);
        mVehicleImageSelectPicture.selectMultiPicture(this, new SelectPicture.OnSelectResultCallback() {
            @Override
            public void selectResultCallback(List<LocalMedia> selectList) {

                if (null != selectList && selectList.size() > 0) {

                    mVehicleImageSelectPictureList.clear();

                    int size = selectList.size();
                    String path = "";
                    for (int i = 0; i < size; i++) {//判断是不是网络图片

//                            path = selectList.get(i).getCompressPath();
                            path = selectList.get(i).getPath();
                            requestPictureUpload(PictureType.TYPE_VEHICLE_IMAGE, path, selectList.get(i));

                    }
                }
            }

            @Override
            public void selectResultPath(String path) {

            }

            @Override
            public void deletePictureCallback(List<LocalMedia> selectList, int position) {
                int size = mVehicleImageSelectPictureList.size();
                LogUtil.print("position--" + position + "\n" + "size--" + size);
                if (position < size) {
                    mVehicleImageSelectPictureList.remove(position);

                }

            }
        }, getVehicleImageRecyclerView());
    }

    public RecyclerView getVehicleImageRecyclerView() {
        return rv_shenhe_image;
    }

    private void requestPictureUpload(int type, String path, LocalMedia localMedia) {
        if (TextUtils.isEmpty(path)) return;
//        //添加水印
//        Bitmap bitmap = ImageUtil.getBitmap(path);
        File file=new File(path);//ImageUtil.getFile(bitmap)
        uploadPicture(type, file, localMedia);
    }

    private void uploadPicture(int type, File file, LocalMedia localMedia) {
        UploadPictureInfo uploadPictureInfo = new UploadPictureInfo();
        uploadPictureInfo.file = file;
        uploadPictureInfo.pictureModule = "dispatchSource";
        new UploadPicture(new IUploadPicture.UploadPictureCallback() {
            @Override
            public void onSuccess(UploadPictureInfo uploadPictureInfo, PictureInfo pictureInfo) {
                processPictureUploadResult(pictureInfo, type);
            }

            @Override
            public void onFailed(UploadPictureInfo uploadPictureInfo) {
                removePicture(type, localMedia);
            }
        }).uploadPicture(this, uploadPictureInfo);

    }

    private void removePicture(int type, LocalMedia localMedia) {
//        if (type == PictureType.TYPE_INVOICES_IMAGE) {
//            mSelectPicture.removePicture(localMedia);
//        } else
        if (type == PictureType.TYPE_VEHICLE_IMAGE) {
            mVehicleImageSelectPicture.removePicture(localMedia);
        }
    }

    private void processPictureUploadResult(PictureInfo pictureInfo, int type) {
//        switch (type) {
//            case PictureType.TYPE_INVOICES_IMAGE:
//                mSelectPictureList.add(pictureInfo.id);
//                break;
//            case PictureType.TYPE_VEHICLE_IMAGE:


        shenPiTiJiaoOneBean.setAttachment(pictureInfo.id);

        mVehicleImageSelectPictureList.add(pictureInfo.id);
//        WantBuyDetailBean.ImageDTO imageDTO=new WantBuyDetailBean.ImageDTO();
//        imageDTO.setImageId(pictureInfo.imageId+"");
//        imageDTO.setFileId(pictureInfo.fileId+"");
//        imageDTO.setFilePath(pictureInfo.filePath);
//        selectImageList.add(imageDTO);

//                break;
//        }
        LogUtil.print("pictureID---" + pictureInfo.id);
    }




    private void postShenHeInfo() {


        driverModel.postShenHeIsTong(this, shenPiTiJiaoOneBean, true, this.bindLifecycle(),
                new ObserverResponseListener<CommonResponse>() {
                    @Override
                    public void onNext(CommonResponse commonResponse) {
                        if (!isFinishing() && !isDestroyed()) {
                            if (commonResponse.getCode() == 20000) {
                                EventBusManage.refreshContractList();
                                openActivity(HeTongShenTwoActivity.class);
                            } else {
                                showToast(commonResponse.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseThrowable e) {

                        showToast(e.message);
                    }
                });
    }


    private void getShenHeInfo() {
        Map<String, String> map = new HashMap<>();
        map.put("type","2");
        map.put("contractno",contractno);
        driverModel.getShenHeInfo(this, map, true, this.bindLifecycle(),
                new ObserverResponseListener<CommonResponse<ShenPiTiJiaoOneBean>>() {
                    @Override
                    public void onNext(CommonResponse<ShenPiTiJiaoOneBean> commonResponse) {
                        if (!isFinishing() && !isDestroyed()) {
                            if (commonResponse.getCode() == 20000) {
                                shenPiTiJiaoOneBean = commonResponse.getData();

                                shenPiTiJiaoOneBean.setContractno(contractno);
                                String last = shenPiTiJiaoOneBean.getLast();
                                if("1".equals(last)){
                                    tv_zhongshen.setVisibility(View.VISIBLE);
                                }else {
                                    tv_zhongshen.setVisibility(View.GONE);
                                }

                                if ("1".equals(shenPiTiJiaoOneBean.getEnd())){//总裁隐藏终审
                                    tv_zhongshen.setVisibility(View.GONE);
                                    civ_duixiang.setVisibility(View.GONE);
                                }

                                if (!TextUtils.isEmpty(shenPiTiJiaoOneBean.getPlanuser())){//有下一级审批人的隐藏
                                    civ_duixiang.setVisibility(View.GONE);
                                }


                                civ_jiedian.setContent(shenPiTiJiaoOneBean.getName());
                                civ_duixiang.setContent(shenPiTiJiaoOneBean.getPlanusername());
                                shenPiTiJiaoOneBean.setPlanuser(shenPiTiJiaoOneBean.getPlanuser());

                            } else {
                                showToast(commonResponse.getMsg());
                            }
                        }
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseThrowable e) {

                        showToast(e.message);
                    }
                });
    }


    private void showCreateTipDialog(ContractInfo contractInfo) {
        new MaterialDialog.Builder(getContext())
                .content("是否生成提交？")
                .positiveText("是")
                .negativeText("否")
                .onPositive(new MaterialDialog.SingleButtonCallback() {
                    @Override
                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                        createContract(contractInfo);
                    }
                })
                .show();
    }

    private ContractModel contractModel;
    private void createContract(ContractInfo contractInfo) {
        Map<String, String> map = new HashMap<>();
        map.put("id", contractInfo.id);
        map.put("type", "1");
        contractModel.createContractModel(getContext(), map, true, this.bindLifecycle(), new ObserverResponseListener<CommonResponse>() {
            @Override
            public void onNext(CommonResponse commonResponse) {
//                showToast(commonResponse.getMsg());
                String token = SharedPreferenceManager.getInstance().getToken();
                String pdfUrl = Config.baseUrl+"contract/contractView?fileName="+mContractInfo.contractno+"&token="+token;
                webView.loadUrl("file:///android_asset/indexpdf.html?" + pdfUrl);
            }

            @Override
            public void onError(ExceptionHandle.ResponseThrowable e) {
                showToast(e.message);
            }
        });
    }



}
